package com.topboya.linker.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.topboya.linker.R;
import com.topboya.linker.diyview.CenteredEditText;
import com.topboya.linker.diyview.group.GroupItemDecoration;
import com.topboya.linker.diyview.group.GroupRecyclerView;
import com.topboya.linker.model.levelitem.SelectProductGroup;
import com.topboya.linker.model.response.LatelyDataResponse;
import com.topboya.linker.model.response.ProductInforListReponse;
import com.topboya.linker.model.response.SelectFileResponse;
import com.topboya.linker.ui.adapter.SearchProductAdapter;
import com.topboya.linker.ui.adapter.SelectProductAdapter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.presenter.ProduceInfoPresenter;
import com.topboya.linker.ui.view.ProduceInfoView;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

public class SearchProductInforActivity extends BaseActivity<ProduceInfoView, ProduceInfoPresenter> implements ProduceInfoView {

    private static final String TAG = "SellectProductInforActivity:";
    private Toolbar toolbar;
    private RecyclerView recycle_search_produceinfo;
    private CenteredEditText et_search_devices;
    private TextView toolbar_title;
    private TextView tv_toolbar_right;
    private Button btn_select;
    private Button btn_selected;
    private RelativeLayout rl_selectall;
    private CheckBox ck_selectall;
    private  ArrayList<SelectFileResponse.FileList> selectFileList;
    private ArrayList<ProductInforListReponse.ProductDetailInfoList> productDetailInfoLists;
//    上次选中的状态，在下次还要被选中
    private ArrayList<SelectProductGroup> productoListslateselect;
    private List<SelectProductGroup> selectProductGroups;
    private SearchProductAdapter searchProductAdapter;
    private int pageNo =1;
    private boolean isearch;
    private String position;
    @Override
    protected int getLayoutId() {

        return R.layout.activity_search_productinfo;
    }

    @Override
    protected void initView() {

        isearch = false;
        toolbar = findViewById(R.id.toolbar);
        recycle_search_produceinfo = findViewById(R.id.recycle_search_produceinfo);
        toolbar_title = findViewById(R.id.toolbar_title);
        btn_select = findViewById(R.id.btn_select);
        btn_selected = findViewById(R.id.btn_selected);
        tv_toolbar_right = findViewById(R.id.tv_toolbar_right);
        ck_selectall = findViewById(R.id.ck_selectall);
        et_search_devices = findViewById(R.id.et_search_devices);
        rl_selectall = findViewById(R.id.rl_selectall);
    }

    @Override
    protected void initData() {

        toolbar_title.setText("选择产品");
        tv_toolbar_right.setVisibility(View.GONE);
        selectFileList =new ArrayList<>();
        selectProductGroups = new ArrayList<>();
        productDetailInfoLists = new ArrayList<>();
        productoListslateselect=(ArrayList<SelectProductGroup>) getIntent().getSerializableExtra("productDetailInfoList");
        if (null !=productoListslateselect){

            btn_selected.setText("已选择："+productoListslateselect.size());
        }

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
//      为代  item下面横线向目前是在条目布局加了一个view，后面改码设置
        searchProductAdapter = new SearchProductAdapter(this, selectProductGroups);
        recycle_search_produceinfo.setLayoutManager(layoutManager);
        recycle_search_produceinfo.setAdapter(searchProductAdapter);


    }
    public static void hideKeyboard(View view) {

        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Override
    protected void initListener() {

        et_search_devices.setOnEditorActionListener((v, actionId, event) -> {

            String searchkey = v.getText().toString().trim();
            mPresenter.getProductInforList(String.valueOf(pageNo),searchkey,"1");
            hideKeyboard(v);

            return false;
        });


        toolbar.setNavigationOnClickListener(v -> back());
        searchProductAdapter.setOnItemClickListener((v, position) -> {

            btn_selected.setText("已选择：");

        });

        btn_selected.setOnClickListener(v -> {

            ArrayList<SelectProductGroup> productDetailInfoList= searchProductAdapter.getSelectedItem();
            if (null ==productDetailInfoList || productDetailInfoList.size() ==0){

                UIUtils.showToast("为选择产品，请先选择");
                return;
            }
            Intent intent = new Intent(SearchProductInforActivity.this,SeeSelectedProductActivity.class);
            intent.putExtra("productDetailInfoList",productDetailInfoList);
            startActivity(intent);


        });

        btn_select.setOnClickListener(v -> {

            //返回选择的产品集合
            ArrayList<SelectProductGroup> productDetailInfoList= searchProductAdapter.getSelectedItem();
            backTostartActivity(productDetailInfoList);

        });

    }

    @Override
    protected ProduceInfoPresenter createPresenter() {

        return new ProduceInfoPresenter(this);
    }


    @Override
    public void setProductInfoCustomeData(ArrayList<ProductInforListReponse.ProductDetailInfoList> productDetailInfoLists,String count) {

            this.productDetailInfoLists.addAll(productDetailInfoLists);

            if (null !=productoListslateselect && productoListslateselect.size() >0){

                for (SelectProductGroup productDetailInfoList: productoListslateselect){

                    searchProductAdapter.setItemChecked(productDetailInfoList.getId(),productDetailInfoList);
                }
            }
        for (int i = 0; i < productDetailInfoLists.size(); i++) {

            SelectProductGroup selectProductGroup = new SelectProductGroup();
            selectProductGroup.setProductName(productDetailInfoLists.get(i).getProductName());
            selectProductGroup.setId(productDetailInfoLists.get(i).getId());
            selectProductGroup.setProductFactory(productDetailInfoLists.get(i).getProductFactory());
            selectProductGroup.setFileNum(productDetailInfoLists.get(i).getFileNum());
            selectProductGroups.add(selectProductGroup);

        }
         searchProductAdapter.notifyDataSetChanged();


    }

    @Override
    public void setLatelyData(List<LatelyDataResponse.Data> latelyData) {



    }

    private void backTostartActivity(ArrayList<SelectProductGroup> productDetailInfoList) {

        //数据是使用Intent返回
        Intent intent = new Intent();
        //把返回数据存入Intent
        intent.putExtra("productDetailInfoList", productDetailInfoList);
        intent.putExtra("isDoc", false);
//        intent.putExtra("fileLists", fileListss);
        //设置返回数据
        setResult(1002, intent);
        //关闭Activity
        finish();
    }

    //   返回选择的资料，遍历拿资料的时候直接去选中的产品集合中遍历，不用从总得集合中遍历，这样就节约很多时间
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
         LogUtils.v(TAG + "intent:"+intent);
        if (null !=intent){

            LogUtils.v(TAG +"requestCode:"+requestCode+"--resultCode"+resultCode);

            ArrayList<SelectFileResponse.FileList> fileLists= (ArrayList<SelectFileResponse.FileList>) intent.getSerializableExtra("fileLists");
//            拿到资料信息中
            position = intent.getStringExtra("position");
            LogUtils.v(TAG+"position"+position);
            selectProductGroups.get(Integer.valueOf(position)).setFileLists(fileLists);
            searchProductAdapter.notifyDataSetChanged();
            LogUtils.v(TAG+"position"+position+"fileLists:"+fileLists.size());
        }
    }

    @Override
    public void onBackPressed() {

        back();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        } else { // 如果不是back键正常响应
            return super.onKeyDown(keyCode, event);
        }
    }

    private void back() {

        ArrayList<SelectProductGroup> productDetailInfoList= searchProductAdapter.getSelectedItem();
        backTostartActivity(productDetailInfoList);

    }


}